<template>
  <div>
    <el-card>
      <el-form inline class="search_form">
        <el-form-item label="用户名：">
          <el-input placeholder="请输入用户名" v-model="searchName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getUserList(1)" :disabled="tableLoading">搜索</el-button>
          <el-button type="primary" plain @click="searchName = ''" :disabled="!searchName">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table_box">
      <el-form inline>
        <el-form-item>
          <el-button type="primary" @click="addUser">添加用户</el-button>
          <el-button type="primary" color="#626aef" :disabled="!selectIdList.length" @click="delInbatch">批量删除</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="tableLoading"
        :data="tableData"
        border
        style="margin: 10px 0; width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" />
        <el-table-column align="center" label="#" type="index" />
        <el-table-column align="center" label="id" prop="id" />
        <el-table-column align="center" label="用户名" prop="username" show-overflow-tooltip />
        <el-table-column align="center" label="用户昵称" prop="name" show-overflow-tooltip />
        <el-table-column align="center" label="角色" prop="roleName" show-overflow-tooltip />
        <el-table-column align="center" label="创建时间" prop="createTime" show-overflow-tooltip />
        <el-table-column align="center" label="更新时间" prop="updateTime" show-overflow-tooltip />
        <el-table-column align="center" label="操作" width="300px" class="btn_box">
          <template #="{ row }">
            <el-button type="primary" icon="user" size="small" @click="handleRole(row)">分配角色</el-button>
            <el-button type="primary" icon="edit" size="small" @click="handleEdit(row)">编辑</el-button>

            <el-popconfirm title="确认删除？" @confirm="handleDel(row)">
              <template #reference>
                <el-button type="primary" icon="delete" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="prev, pager, next,jumper, ->, sizes,total"
        :total="total"
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 10]"
        background
        @current-change="getUserList"
        @size-change="handleSizeChange"
      />
    </el-card>
    <el-drawer v-model="showDrawer" direction="rtl" size="30%" class="drawer_box">
      <template #header>
        <h2>{{ userParams.id ? "编辑用户" : "添加用户" }}</h2>
      </template>
      <template #default>
        <el-form :model="userParams" :rules="userRules" ref="userRef">
          <el-form-item label="用户名称：" prop="username">
            <el-input placeholder="请输入用户名" v-model="userParams.username"></el-input>
          </el-form-item>
          <el-form-item label="用户昵称：" prop="name">
            <el-input placeholder="请输入用户昵称" v-model="userParams.name"></el-input>
          </el-form-item>
          <el-form-item label="用户密码：" prop="password" v-if="!userParams.id">
            <el-input placeholder="请输入用户密码" v-model="userParams.password"></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">确认</el-button>
      </template>
    </el-drawer>
    <el-drawer v-model="showRoleDrawer" direction="rtl" size="30%" class="drawer_box">
      <template #header>
        <h2>分配角色（职位）</h2>
      </template>
      <template #default>
        <el-form :model="userParams" :rules="userRules" ref="userRef">
          <el-form-item label="用户名称：">
            <el-input v-model="userParams.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="角色列表：">
            <el-checkbox v-model="checkAllRole" :indeterminate="isIndeterminate" @change="handleCheckAllRoleChange"
              >全选</el-checkbox
            >
            <el-checkbox-group v-model="userRoles" @change="handleCheckedRoleChange">
              <el-checkbox v-for="role in allRoles" :key="role.id" :label="role">{{ role.roleName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <el-button @click="handleRoleCancle">取消</el-button>
        <el-button type="primary" @click="handleRoleConfirm">确认</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick } from "vue";
import { reqAddUser, reqUserList, reqRoleList, reqSetRole, reqDelUser } from "@/api/acl/user";
import type { UserResponseData, Records, User, RoleList, SetRoleData, DelUserData } from "@/api/acl/user/type";
import { ElMessage } from "element-plus";

let tableLoading = ref<boolean>(false);
let searchName = ref<string>(""); // 搜索用户名

let tableData = ref<Records>([]); // 表格数据
let selectIdList = ref<number[]>([]); // 多选的数据
let total = ref<number>(0); // 表格总数
let pageNo = ref<number>(1); // 表格页
let pageSize = ref<number>(5); // 表格每页数量

let showDrawer = ref<boolean>(false); // 控制抽屉（新增/编辑 功能）显示
let userParams = ref<User>({
  id: undefined,
  username: "",
  password: "",
  name: ""
}); // 表单填入信息

let userRef = ref(); // 新增/编辑表单
let userRules = {
  username: [{ required: true, trigger: "blur", min: 5, message: "用户名至少5位" }],
  name: [{ required: true, trigger: "blur", min: 3, message: "昵称至少3位" }],
  password: [{ required: true, trigger: "blur", min: 6, message: "密码至少6位" }]
}; // 表单校验

let showRoleDrawer = ref<boolean>(false); //分配角色显示
let allRoles = ref<RoleList>([]); // 全部角色列表
let userRoles = ref<RoleList>([]); // 用户角色列表
let checkAllRole = ref<boolean>(false); //抽屉角色是否全选
let isIndeterminate = ref<boolean>(false); // 抽屉角色是否选择了一部分
// ---------------------------------------//
// 初始化时获取用户列表
onMounted(() => {
  getUserList();
});
// ---------------------------------------//
// 获取用户列表
const getUserList = async (pager = 1) => {
  pageNo.value = pager;
  tableLoading.value = true;
  const res: UserResponseData = await reqUserList(pageNo.value, pageSize.value, searchName.value);
  tableLoading.value = false;
  console.log(res);
  if (res.code === 200) {
    total.value = res.data.total;
    tableData.value = res.data.records;
  }
};
// -----------------表格----------------------//
// 点击批量删除
const delInbatch = async () => {
  const res = await reqDelUser({ userIdList: selectIdList.value });
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功！"
    });
    let page = tableData.value.length > selectIdList.value.length ? pageNo.value : pageNo.value - 1;
    getUserList(page || 1);
  } else {
    ElMessage({
      type: "error",
      message: res.message
    });
  }
};
// 点击表格多选
const handleSelectionChange = (val: User[]) => {
  // console.log(val);
  selectIdList.value = val.map((item: User) => item.id) as number[];
};
// 点击切换表格每页数量
const handleSizeChange = () => {
  getUserList();
};
// 点击表格删除单个
const handleDel = async (row: User) => {
  // console.log(row.id);
  const data: DelUserData = {
    userIdList: [row.id as number]
  };
  const res = await reqDelUser(data);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "删除成功！"
    });
    let page = tableData.value.length > 1 ? pageNo.value : pageNo.value - 1;
    getUserList(page || 1);
  } else {
    ElMessage({
      type: "error",
      message: res.message
    });
  }
};
// --------------用户弹窗-------------------------//
// 新建用户弹窗
const addUser = () => {
  openDrawer();
  // 清空form
  Object.assign(userParams.value, { id: undefined, username: "", password: "", name: "" });
};
// 编辑用户弹窗
const handleEdit = (row: User) => {
  // console.log(row);
  openDrawer();
  Object.assign(userParams.value, { id: row.id, username: row.username, name: row.name });
};
// 打开抽屉 清空内容
const openDrawer = () => {
  showDrawer.value = true;
  nextTick(() => {
    userRef.value.clearValidate("username");
    userRef.value.clearValidate("name");
    userRef.value.clearValidate("password");
  });
};
// 抽屉确认
const handleSave = async () => {
  await userRef.value.validate();
  const res: any = await reqAddUser(userParams.value);
  console.log(res);
  if (res.code === 200) {
    showDrawer.value = false;
    getUserList(pageNo.value);
    ElMessage({
      type: "success",
      message: "修改成功"
    });
  } else {
    ElMessage({
      type: "error",
      message: res.message
    });
  }
};
// 抽屉取消
const handleCancel = () => {
  showDrawer.value = false;
  Object.assign(userParams.value, { id: undefined, username: "", password: "", name: "" });
};
// -----------------角色弹窗----------------------//
// 打开分配角色抽屉
const handleRole = async (row: User) => {
  // console.log(row.id);
  showRoleDrawer.value = true;
  Object.assign(userParams.value, { id: row.id, username: row.username, name: row.name });
  const res = await reqRoleList(row.id as number);
  // console.log(res);
  if (res.code === 200) {
    allRoles.value = res.data.allRoleList;
    userRoles.value = res.data.assignRoles;
    const checkedCount = userRoles.value.length;
    checkAllRole.value = checkedCount === allRoles.value.length;
    isIndeterminate.value = checkedCount > 0 && checkedCount < allRoles.value.length;
  } else {
    ElMessage({
      type: "error",
      message: res.message
    });
  }
};
// 点击角色列表全选
const handleCheckAllRoleChange = (val: boolean) => {
  userRoles.value = val ? allRoles.value : [];
  isIndeterminate.value = false;
};
// 点击单独选择角色
const handleCheckedRoleChange = (val: string[]) => {
  console.log(val);
  const checkedCount = val.length;
  checkAllRole.value = checkedCount === allRoles.value.length;
  isIndeterminate.value = checkedCount > 0 && checkedCount < allRoles.value.length;
};
// 取消角色修改
const handleRoleCancle = () => {
  showRoleDrawer.value = false;
  isIndeterminate.value = false;
  checkAllRole.value = false;
  Object.assign(userParams.value, { id: undefined, username: "", password: "", name: "" });
};
// 确认角色修改
const handleRoleConfirm = async () => {
  // console.log(userParams.value, userRoles.value);
  let data: SetRoleData = {
    userId: userParams.value.id as number,
    roleIdList: userRoles.value.map(item => item.id)
  };
  const res = await reqSetRole(data);
  if (res.code === 200) {
    ElMessage({
      type: "success",
      message: "设置角色成功！"
    });
    handleRoleCancle();
    getUserList(pageNo.value);
  } else {
    ElMessage({
      type: "error",
      message: res.message
    });
  }
};
// ---------------------------------------//
</script>

<style scoped lang="scss">
.search_form {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-form-item {
    margin: 0;
  }
}

.table_box {
  margin-top: 10px;
  .btn_box {
    display: flex;
    justify-content: space-around;
  }
}
.drawer_box {
  .el-form-item {
    margin: 20px 0;
  }
}
</style>
